package cn.wedding.filter;

import cn.wedding.entity.Admin;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AuthFilter implements Filter {
    private String exclude;
    private String[] excludes;
    public void init(FilterConfig config) throws ServletException {
        exclude = config.getInitParameter("exclude");
        excludes = exclude.split(",");
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        boolean isExclude = false;

        for (String s : excludes) {
            if (request.getServletPath().contains(s)) {
                isExclude = true;
                break;
            }
        }
        if (isExclude) {
            //要排除的路径
            chain.doFilter(req, resp);
        } else {
            Admin admin = (Admin) session.getAttribute("admin");
            if (null == admin) {
                response.sendRedirect("/admin/admin.jsp");
            } else {
                chain.doFilter(req, resp);
            }
        }
    }
}
